import { defineStore } from "pinia";
import auto from "@/plugins/auto";
import { getRouters } from "@/api/menu";
import router, { constantRoutes, dynamicRoutes } from "@/router/index.js";
import Layout from "@/Layout/index.vue";
const modules = import.meta.glob("./../views/**/*.vue"); //动态加载

export const usePermissionStore = defineStore("perimission", {
  state: () => ({

    //菜单路由
    sidebarRouters: [],
    indexPage: "", //默认首页
  }),
  actions: {
    setSidebarRouters(routes) {
      this.sidebarRouters = routes;
    },
    // setDefaultRoutes(routes) {
    //   this.defaultRoutes = constantRoutes.concat(routes);
    // },
    setIndexPages(indexPage) {
      this.indexPage = indexPage;
    },
    generateRoutes() {
      return new Promise((resolve, reject) => {
        getRouters().then((res) => {
          let firseridnex;
          if (res?.data && res.data.length > 0) {
            firseridnex = chilrenpath(res.data[0]);
            firseridnex = firseridnex.replace("//", "/");
          }
          const sdata = JSON.parse(JSON.stringify(res.data));
          const sidebarRoutes = filterAsyncRouter(sdata);
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
          asyncRoutes.forEach((route) => {
            router.addRoute(route);
          });
          this.setSidebarRouters(constantRoutes.concat(sidebarRoutes));
          // this.setDefaultRoutes(sidebarRoutes);
          this.setIndexPages(firseridnex);
   
          resolve(sidebarRoutes); //返回路由
        });
      });
    },
  },
});
function chilrenpath(item) {
  if (item.children && item.path && item.children.length > 0) {
    return item.path + "/" + chilrenpath(item.children[0]);
  } else {
    return item?.path;
  }
}
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter((route) => {
    if (route.component) {
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        route.component = loadview(route.component);
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    } else {
      delete route["children"];
    }
    return true;
  });
}
function loadview(view) {
  let res;
  for (const path in modules) {
    //views后面一个/vue前面一个
    const views = path.split("views/")[1].split(".vue")[0];
    if (views === view) {
      res = () => modules[path]();
    }
  }
  console.log(res,'res');
  
  return res;
}
function filterDynamicRoutes(routers) {
  const res = [];
  routers.forEach((route) => {
    if (route.permissions) {
      if (auto.hasPermiOr(route.permissions)) {
        res.push(route); //有权限的添加到路由中
      }
    } else if (route.roles) {
      if (auto.hasRoleOr(route.roles)) {
        res.push(route); //有权限的添加到路由中
      }
    }
  });
  return res;
}
